package com.siwei.apply.controller;

import com.siwei.apply.domain.res.YdbpRes;
import com.siwei.apply.domain.vo.YdbpUpdateVo;
import com.siwei.apply.domain.vo.YdbpVo;
import com.siwei.apply.service.YdbpService;
import com.siwei.common.core.domain.R;
import com.siwei.common.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用地报批 控制器
 * 单独选址第二步
 */
@RestController
@RequestMapping("/ydbp")
public class YdbpController extends BaseController {
    @Autowired
    private YdbpService ydbpService;

    /**
     * 添加用地报批
     */
    @PostMapping()
    public R<Map> Add(@RequestBody YdbpVo ydbpVo) {
        try {
            Boolean b = ydbpService.isExit(ydbpVo.getProjectId());
            if (b == true) {
                return R.fail("此项目已添加用地报批");
            }
            String id = ydbpService.add(ydbpVo);
            Map<String, String> map = new HashMap<>();
            map.put("id", id);
            return R.ok(map);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取用地报批
     *
     * @param projectId 项目ID
     * @return 用地报批
     */
    @GetMapping("/{projectId}")
    public R<YdbpRes> Get(@PathVariable String projectId) {
        try {
            return R.ok(ydbpService.get(projectId));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 通过主键id获取用地报批，返回结果与按projectId查询一致
     */
    @GetMapping("/id/{id}")
    public R<YdbpRes> GetById(@PathVariable String id) {
        try {
            return R.ok(ydbpService.getById(id));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 更新用地报批
     *
     * @param ydbpUpdateVo 用地用地报批
     * @return 操作结果
     */
    @PutMapping()
    public R<Void> Update(@RequestBody YdbpUpdateVo ydbpUpdateVo) {
        try {
            ydbpService.update(ydbpUpdateVo);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 更新用地报批的上链状态
     */
    @PutMapping("/onchain")
    public R<Void> updateHasOnchain(@RequestBody Map<String, Object> params) {
        try {
            String id = (String) params.get("id");
            Boolean hasOnchain = (Boolean) params.get("hasOnchain");
            ydbpService.updateHasOnchain(id, hasOnchain);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}
